<script setup lang="ts">
definePageMeta({
  layout: "default-custom",
  title: "搜索",
  i18n: "menu.search",
});
import { saveCollectApi, gameUrlApi } from "@/api/home";
import { gameSubItemApi } from "@/api/home";
import type { WebIframe } from "@/api/model/home";
const emits = defineEmits(["gameClick"]); // 定义事件
const { t } = useI18n();
const router = useRouter();
const configStore = useConfigStore();
const goBack = () => {
  router.go(-1);
};
const userStore = useUserStore();
const search = ref("");
const menuAactive = ref(0);
const categoryList = ref([]);
const showWebView = ref(false);
const gameWeb = ref<WebIframe>({
  gold: 0,
  name: "",
  webViewUrl: "",
});
const handleClick = (item: any) => {
  if (!userStore.isLogin) return router.push("/login");
  showWebView.value = true;
  gameUrlApi({ gameId: item.gameId }).then((res) => {
    gameWeb.value = {
      gold: 999.99,
      name: item.name,
      webViewUrl: res,
    };
  });
};
// 更多弹窗数组
const columns = [
  { value: 1, text: t("home_page.leftMenu.hots") },
  { value: 2, text: t("home_page.leftMenu.slots") },
  { value: 3, text: t("home_page.leftMenu.chess") },
  { value: 4, text: t("home_page.leftMenu.fish") },
  { value: 5, text: t("home_page.leftMenu.person") },
  { value: 6, text: t("home_page.leftMenu.sport") },
  { value: 7, text: t("home_page.leftMenu.lottery") },
];
const showPicker = ref(false);
const handlePickerConfirm = (selectedValues: number[]) => {
  console.log("选中的值:", selectedValues);
  // 处理选中的值
};
const collectArr = ref([]);
onMounted(() => {
  let type = configStore.moreParams.type;
  if (type) getGameSubItemApi(type);
});
const titleArr = [
  { sid: 4, name: "ALL" },
  { sid: 0, name: "LUVA" },
  { sid: 1, name: "JILI" },
  { sid: 2, name: "PP" },
  { sid: 3, name: "PG" },
];
const getGameSubItemApi = (type: number) => {
  gameSubItemApi(type).then((res) => {
    collectArr.value = res.collects || []; // 收藏的游戏ID数组 [1,2,3,4]

    // 创建游戏数据时检查收藏状态
    const createGameItem = (game: { gameId: any }) => ({
      ...game,
      active: collectArr.value.some((id) => id === game.gameId), // 精确匹配gameId
    });

    // 按照sid分组
    const groupedBySid = res.list.reduce(
      (cur: { [x: string]: any[] }, game: { sid: any }) => {
        const sid = game.sid;
        if (!cur[sid]) {
          cur[sid] = [];
        }
        cur[sid].push(createGameItem(game));
        return cur;
      },
      {}
    );

    // 转换为categoryList格式
    const newCategoryList = Object.entries(groupedBySid).map(([sid, games]) => {
      const titleObj = titleArr.find((t) => t.sid === parseInt(sid));
      return {
        title: titleObj?.name || `分类${sid}`,
        gameArr: games.map((g: { gameId: any }) => ({
          ...g,
          active: collectArr.value.some((id) => id === g.gameId), // 再次确认收藏状态
        })),
      };
    });

    // 添加ALL分类（包含所有游戏）
    newCategoryList.unshift({
      title: "ALL",
      gameArr: res.list.map((game: { gameId: any }) => ({
        ...game,
        active: collectArr.value.some((id) => id === game.gameId),
      })),
    });
    categoryList.value = newCategoryList;
  });
};
// 收藏和取消收藏
const toCollect = async (v: any) => {
  if (!userStore.isLogin) return router.push("/login");
  try {
    let res = await saveCollectApi({ gameId: v.gameId, add: !v.active });
    v.active = !v.active;
    showSuccessToast(v.active ? "收藏成功！" : "取消收藏成功！");
  } catch (error) {
    showFailToast("收藏失败！");
  }
};
</script>

<template>
  <!-- WebView弹窗 -->
  <div v-if="showWebView" class="iframe">
    <GameWeb
      :game-data="gameWeb"
      @close="showWebView = $event"
      allow="fullscreen"
    />
  </div>
  <div v-else class="more-box" mx-auto text-16 text-dark dark:text-white>
    <!-- 固定区域 -->
    <div class="fixed-header">
      <!-- 状态栏 -->
      <div class="top">
        <div class="flex items-center">
          <div
            class="w-28 h-28 bg-#394243 rounded-5 flex items-center justify-center mr-10"
          >
            <van-icon name="arrow-left" @click="goBack" color="#868689" />
          </div>
          <div class="color-#ffffff font-bold">
            {{ configStore.moreParams.name }}
          </div>
        </div>
        <div
          class="w-28 h-28 bg-#394243 rounded-5 flex items-center justify-center"
        >
          <img
            src="/imgs/more.png"
            alt=""
            class="w-15"
            @click="showPicker = true"
          />
        </div>
      </div>

      <!-- 搜索框 -->
      <van-field placeholder="输入关键词" :border="false" class="search-field">
        <template #left-icon>
          <van-icon name="search" class="search" color="#b6b6b6" />
        </template>
        <template #right-icon>
          <img
            src="/imgs/search_close.png"
            alt=""
            class="w-18"
            @click="search = ''"
            v-if="search"
          />
        </template>
      </van-field>

      <!-- 菜单栏 -->
      <van-tabs v-model:active="menuAactive" swipeable class="tabs sticky-tabs">
        <van-tab v-for="(item, index) in categoryList" :key="item.title">
          <template #title>
            <div class="flex items-center">
              <span
                :class="menuAactive == index ? 'color-#eef3ff' : 'inactive'"
              >
                {{ item.title }}</span
              >
            </div>
          </template>
        </van-tab>
      </van-tabs>
    </div>

    <!-- 可滚动内容区域 -->
    <div class="scroll-content">
      <div v-for="(item, index) in categoryList" :key="item.title">
        <!-- 游戏图 -->
        <div class="game-box" v-show="menuAactive === index">
          <div
            v-for="(v, i) in item.gameArr"
            :key="i"
            class="item-img"
            @click="handleClick(v)"
          >
            <img :src="v.icon" alt="" class="game-img" />
            <img
              src="/imgs/hot_logo.png"
              alt=""
              v-if="v.hot"
              class="hot-logo"
            />
            <!-- <div class="title">{{ v.name }}</div> -->
            <div class="collect" @click.stop="toCollect(v)">
              <img
                :src="v.active ? '/imgs/collect.png' : '/imgs/collect_un.png'"
                alt=""
                class="w-25 mr-3"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 更多弹窗 -->
    <GamePicker
      v-model:show="showPicker"
      :columns="columns"
      title="选择游戏"
      @confirm="handlePickerConfirm"
    />
  </div>
</template>
<style scoped lang="css">
.iframe {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  /* 关键 */
  position: fixed;
  /* 固定定位 */
}
.add {
  width: 55%;
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
}

.center-title {
  position: absolute;
  top: 15px;
  right: 40%;
  transform: translateX(-50%);
}

::v-deep .van-tabs__content.van-tabs__content--animated {
  overflow: visible;
}

::v-deep .van-swipe.van-tabs__track {
  overflow: visible;
}

.search::after {
  display: inline-block;
  content: "";
  width: 1px;
  height: 18px;
  margin-left: 10px;
  vertical-align: -2px;
  background: #888888;
}

::v-deep .van-field__left-icon {
  background: transparent;
  margin-right: 0;
  margin-right: -3px;
  padding-top: 5px;
  padding-left: 10px;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}

::v-deep .van-field__control {
  font-size: 15px;
  color: #fefffe;
}

::v-deep .van-cell {
  background: url("/imgs/search_bg.png") no-repeat;
  background-size: 100% 100%;
  padding: 0;
}

::v-deep .van-cell__value {
  padding: 5px 10px;
  /* border: 1px solid #f5f6f8; */
  /* border-radius: 5px; */
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  background-color: transparent;
}

::v-deep .van-tabs__line {
  background: transparent;
}

.tabs .tab-item {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  background: #ffffff;
}

::v-deep .tabs .van-swipe-item .van-tab__panel-wrapper {
  background: #ffffff;
}

::v-deep .tabs .van-swipe-item .van-tab__panel-wrapper {
  background: #ffffff;
}

::v-deep .van-tabs__nav {
  background: transparent;
}

::v-deep .van-tabs--line .van-tabs__wrap {
  margin: 10px 0;
}

::v-deep .van-tab {
  margin-top: 7px;
  background: #36353a;
  height: 26px;
  border-radius: 30px;
  margin-right: 8px;
  color: #9a9b9c;
}

::v-deep .van-tab--active {
  margin-top: 7px;
  background: #077cfe;
  height: 26px;
  color: #ffffff;
}

::v-deep .van-tab:last-child {
  margin-right: 0;
}

::v-deep .van-tab--active img {
  width: 22px;
}

/*热门标志图标 */
.hot-logo {
  position: absolute;
  top: -8px;
  /* 向上偏移 */
  left: -3px;
  /* 向左偏移 */
  width: 50px;
  /* 自行根据设计调整 */
  z-index: 2;
  pointer-events: none;
  /* 不影响点击 */
}

.collect {
  position: absolute;
  z-index: 3;
  left: 3px;
  bottom: 3px;
  display: flex;
  align-items: center;
}

.title {
  font-family: HFSuave-Bold;
  position: absolute;
  z-index: 3;
  top: 70%;
  left: 50%;
  transform: translate(-50%, -30%);
  width: 90%;
  font-weight: bold;
  line-height: 16px;
  color: #ffffff;
  word-wrap: break-word;
  /* 允许长单词换行 */
  white-space: normal;
  /* 覆盖默认的 nowrap */
  text-align: center;
  /* 文字居中 */
  padding: 0 5px;
  /* 添加少量内边距 */
}

.logo {
  width: 40%;
  display: flex;
  align-items: center;
  color: #d3c7fd;
  font-size: 12px;
  position: absolute;
  z-index: 3;
  bottom: 0;
  right: 0;
}

.logo .warp {
  width: 60%;
  line-height: 6px;
  word-wrap: break-word;
  /* 允许长单词换行 */
  white-space: normal;
  /* 覆盖默认的 nowrap */
}

.item-img {
  width: 100%;
  height: 140px;
  position: relative;
  border-radius: 8px;
  /* overflow: hidden; */
  flex-shrink: 0;
  /* 防止被压缩 */
}

.bg-img {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 0;
  border-radius: 8px;
}

.game-img {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 1;
  border-radius: 8px;
  /* mask-image: linear-gradient(to bottom, black 35%, transparent 100%);
  -webkit-mask-image: linear-gradient(to bottom, black 35%, transparent 100%);
  mask-size: 100% 100%;
  -webkit-mask-size: 100% 100%; */
}

.webview-overlay {
  display: flex;
  flex-direction: column;
  background-color: #000;
}

.webview-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.webview-header {
  width: 100%;
  height: 60px;
  background-color: #1a1a1a;
  display: flex;
  align-items: center;
  padding: 0 15px;
  color: white;
  font-size: 18px;
}

.webview-content {
  flex: 1;
  width: 100%;
  background-color: white;
}

/* ===== */
.more-box {
  width: 100%;
  height: 100vh;
  background: #222628;
  padding: 0 15px;
  padding-left: 13px;
  position: relative;
}

.fixed-header {
  position: sticky;
  top: 0;
  z-index: 10;
  background: #222628;
}

.top {
  padding: 15px 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.scroll-content {
  height: calc(100vh - 180px);
  /* 根据实际固定区域高度调整 */
  overflow-y: auto;
  padding-bottom: 20px;
}

.sticky-tabs {
  position: sticky;
  top: 90px;
  /* 状态栏+搜索框高度 */
  z-index: 9;
  background: #222628;
}

/* 其他样式保持不变 */
.game-box {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  /* margin-top: 10px; */
}
</style>
